package com.lzy.utils;

import com.google.gson.Gson;
import com.lzy.grace.result.GraceJSONResult;
import com.lzy.grace.result.ResponseStatusEnum;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class RenderErrorUtils {

    public static Mono<Void> display(ServerWebExchange exchange,
                                     ResponseStatusEnum statusEnum){
        // 1.获得响应的response
        ServerHttpResponse response = exchange.getResponse();

        // 2.构建jsonResult
        GraceJSONResult result = GraceJSONResult.exception(statusEnum);

        // 3.设置header类型
        if(!response.getHeaders().containsKey("Content-type")){
            response.getHeaders().add("Content-type",
                    MimeTypeUtils.APPLICATION_JSON_VALUE);
        }

        // 4.修改response的状态码为500
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);

        // 5.转换json并且向response中写入数据
        String resultJson = new Gson().toJson(result);
        DataBuffer buffer =
                response.bufferFactory().wrap(resultJson.getBytes(StandardCharsets.UTF_8));

        return response.writeWith(Mono.just(buffer));
    }
}
